Practice Problems on File Handling in C
Posted on December 18, 2023 by Vishesh Namdev
Python
C
C++
Java
Basic Practice Problems based on chapter which you learn in previous Tutorials.
1. Write a Sentence in File
#include <stdio.h>
int main() {
// Declare variables to store the numbers
int num1, num2;
// Prompt the user to enter the first number
printf("Enter the first number: ");
scanf("%d", &num1);
// Prompt the user to enter the second number
printf("Enter the second number: ");
scanf("%d", &num2);
// Calculate the sum
int sum = num1 + num2;
// Display the result
printf("Sum: %d\n", sum);
return 0;
}
int main() {
// Declare variables to store the numbers
int num1, num2;
// Prompt the user to enter the first number
printf("Enter the first number: ");
scanf("%d", &num1);
// Prompt the user to enter the second number
printf("Enter the second number: ");
scanf("%d", &num2);
// Calculate the sum
int sum = num1 + num2;
// Display the result
printf("Sum: %d\n", sum);
return 0;
}
The fopen function is used to open a file named "example.txt" in write mode ("w").
If the file is successfully opened, the program writes the sentence to the file using fprintf.
Finally, the fclose function is used to close the file.
2. Read the First line
#include <stdio.h>
#include <string>
int main() {
// Open a file for reading
std::ifstream inputFile("example.txt");
// Check if the file is successfully opened
if (!inputFile.is_open()) {
std::cerr << "Error opening the file!" << std::endl;
return 1;
}
// Read the first line from the file
std::string firstLine;
std::getline(inputFile, firstLine);
// Close the file
inputFile.close();
// Display the first line
std::cout << "First line from the file: " << firstLine << std::endl;
return 0;
}
#include <string>
int main() {
// Open a file for reading
std::ifstream inputFile("example.txt");
// Check if the file is successfully opened
if (!inputFile.is_open()) {
std::cerr << "Error opening the file!" << std::endl;
return 1;
}
// Read the first line from the file
std::string firstLine;
std::getline(inputFile, firstLine);
// Close the file
inputFile.close();
// Display the first line
std::cout << "First line from the file: " << firstLine << std::endl;
return 0;
}
The fopen function is used to open the file named "example.txt" in read mode ("r").
If the file is successfully opened, the program uses fgets to read the first line from the file into the line buffer and if the file is empty, a message indicating that the file is empty is printed and the fclose function is used to close the file.